<?php

require_once('Vega/Dao/Table.php');
require_once('Mobitv/Admin/Functions.php');

class Mobitv_Admin_VideoDao extends Vega_Dao_Table {
    /*
     * Hàm lấy thông tin về một video
     * @param $videoId int
     * @relate function getPendingVideoDetail
     */

    public function getDetail($videoId) {
        $sql = "SELECT c.*, ms.address AS server, ms.directory, ms.streaming_address AS streaming_server, a.name AS 'owner', b.fullname AS `subcp_name` FROM clip c LEFT JOIN admin a ON c.member_id=a.id LEFT JOIN `admin` b ON c.subcp_id = b.id LEFT JOIN movie_server ms ON c.ms_id=ms.msID
                WHERE c.id=$videoId";
        $this->_db->query($sql);
        return $this->_db->fetchRow();
    }

    public function getDetailFromAdmin($videoId, $adminId) {
        $sql = "SELECT c.*
                    FROM clip c
                WHERE c.id=$videoId AND (c.member_id=$adminId OR c.subcp_id=$adminId)";
        $this->_db->query($sql);
        return $this->_db->fetchRow();
    }

    public function getList($limit, $page, $userId=0, $condition = '', $visible = 1) {
        $offset = $limit * ($page - 1);
        $_limit = ' LIMIT ' . $limit;
        $_offset = ' OFFSET ' . $offset;
        $_owner = $userId ? " WHERE (c.member_id=$userId OR c.subcp_id=$userId)" : " WHERE 1 ";
        if ($userId) {
            // My video only
            if ($condition == '') {
                $sql = "SELECT c.*, cc.name as category_name 
                        FROM clip c 
                        LEFT JOIN clip_category cc ON c.category_id = cc.id $_owner AND cc.visible = $visible
                        ORDER BY c.created_time DESC
                        $_limit $_offset";
            } else {
                $sql = "SELECT c.*, cc.name as category_name, cd.reason 
                        FROM clip c 
                        LEFT JOIN clip_deleted cd ON c.id=cd.clip_id 
                        LEFT JOIN clip_category cc ON c.category_id = cc.id AND cc.visible = $visible
                        $_owner AND $condition
                        ORDER BY c.created_time DESC
                        $_limit $_offset";
            }
        } else {
            // Video của mọi CP, liệt kê theo trạng thái, thời gian gần nhất trước
            if ($condition != '')
                $sql = "SELECT c.*, cc.name AS category_name
                              FROM clip c
                              LEFT JOIN clip_category cc ON c.category_id = cc.id AND cc.visible = $visible
                              LEFT JOIN tmp_approval ta ON c.id = ta.clip_id
                        WHERE $condition
                        ORDER BY c.created_time DESC 
                        $_limit $_offset";
            else
                $sql = "SELECT c.*, cc.name AS category_name
                        FROM clip c
                        LEFT JOIN clip_category cc ON c.category_id = cc.id AND cc.visible = $visible
                        ORDER BY c.created_time DESC
                        $_limit $_offset";
        }
        //echo $sql;
        $this->_db->query($sql);
        return $this->_db->fetchRowSet();
    }

    public function getInforOfClip($id) {
        $sql = "SELECT c.id
                        ,a1.name AS `owner`
                        ,a2.fullname AS `subcp_name`
                        ,a3.fullname AS `approver`
                    FROM clip c
                        LEFT JOIN `admin` a1 ON c.member_id = a1.id
                        LEFT JOIN `admin` a2 ON c.subcp_id = a2.id
                        LEFT JOIN `admin` a3 ON c.approved_by = a3.id
                    WHERE c.id=$id";
        $this->_db->query($sql);
        return $this->_db->fetchRow();
    }

    public function getList_backup_09012012($limit, $page, $userId=0, $condition = '', $visible = 1) {
        $offset = $limit * ($page - 1);
        $_limit = ' LIMIT ' . $limit;
        $_offset = ' OFFSET ' . $offset;
        $_owner = $userId ? " WHERE (c.member_id=$userId OR c.subcp_id=$userId)" : " WHERE 1 ";
        if ($userId) {
            // My video only
            if ($condition == '') {
                $sql = "SELECT c.*, cc.name as category_name, a.fullname AS `subcp_name`, b.fullname AS `approver`
                        FROM clip c LEFT JOIN `admin` a ON c.subcp_id=a.id
                        LEFT JOIN `admin` b ON c.approved_by=b.id
                        JOIN clip_category cc ON c.category_id = cc.id $_owner AND cc.visible = $visible
                        ORDER BY created_time DESC
                        $_limit $_offset";
            } else {
                $sql = "SELECT c.*, cc.name as category_name, a.fullname AS `subcp_name`, b.fullname AS `approver`, cd.reason
                        FROM clip c
                        LEFT JOIN `admin` a ON c.subcp_id=a.id
                        LEFT JOIN `admin` b ON c.approved_by=b.id
                        LEFT JOIN clip_deleted cd ON c.id=cd.clip_id
                        JOIN clip_category cc ON c.category_id = cc.id AND cc.visible = $visible
                        $_owner AND $condition
                        ORDER BY created_time DESC
                        $_limit $_offset";
            }
        } else {
            // Video của mọi CP, liệt kê theo trạng thái, thời gian gần nhất trước
            if ($condition != '')
                $sql = "SELECT t2. *,
                               ta.admin_id AS approver_id,
                               ta.expired_time
                        FROM (SELECT t1. *,
                                     cc.name AS category_name
                              FROM (SELECT c. *,
                                        a1.name AS `owner`,
                                        a2.fullname AS `subcp_name`,
                                        a3.fullname AS `approver`
                                    FROM clip c
                                        LEFT JOIN `admin` a1 ON c.member_id = a1.id
                                        LEFT JOIN `admin` a2 ON c.subcp_id = a2.id
                                        LEFT JOIN `admin` a3 ON c.approved_by = a3.id
                                    ) t1
                                    LEFT JOIN clip_category cc ON t1.category_id = cc.id AND cc.visible = $visible) t2
                             LEFT JOIN tmp_approval ta ON t2.id = ta.clip_id
                        WHERE (ta.admin_id IS NULL OR ta.admin_id = " . $_SESSION['userid'] . " OR ta.expired_time < now()) AND $condition
                        ORDER BY created_time DESC
                        $_limit $_offset";
            else
                $sql = "SELECT t1.*,
                               cc.name AS category_name
                        FROM (SELECT c.*,
                                a1.name AS `owner`,
                                    a2.fullname AS `subcp_name`,
                                    a3.fullname AS `approver`
                                FROM clip c
                                    LEFT JOIN `admin` a1 ON c.member_id = a1.id
                                    LEFT JOIN `admin` a2 ON c.subcp_id = a2.id
                                    LEFT JOIN `admin` a3 ON c.approved_by = a3.id
                                ) t1
                             LEFT JOIN clip_category cc ON t1.category_id = cc.id AND cc.visible = $visible
                        ORDER BY created_time DESC
                        $_limit $_offset";
        }
        //echo $sql;
        $this->_db->query($sql);
        return $this->_db->fetchRowSet();
    }

    public function getRadioList($catId, $limit, $page, $condition='') {
        $offset = $limit * ($page - 1);
        $_limit = ' LIMIT ' . $limit;
        $_offset = ' OFFSET ' . $offset;
        $condition = $condition ? "AND $condition" : '';

        $sql = "SELECT
                    c.*,
                    cc.name as category_name,
                    a1.name AS `owner`,
                    a2.fullname AS `subcp_name`,
                    a3.fullname AS `approver`
                FROM clip c
                    LEFT JOIN `admin` a1 ON c.member_id = a1.id
                    LEFT JOIN `admin` a2 ON c.subcp_id = a2.id
                    LEFT JOIN `admin` a3 ON c.approved_by = a3.id
                    LEFT JOIN clip_category cc ON c.category_id = cc.id
                WHERE cc.visible=0 $condition
                ORDER BY created_time DESC
                $_limit $_offset";

        $this->_db->query($sql);
        return $this->_db->fetchRowSet();
    }

    public function search($keyword, $page = 1, $limit = 10) {
        // Pagination
        $offset = $limit * ($page - 1);

        $keyword =  mysql_escape_string($keyword);
        $keyword = $this->_db->valueQuote($keyword);
        $sql = "SELECT c.*, cc.name AS category_name, a.name AS 'owner', b.fullname AS `subcp_name`, MATCH(title) AGAINST($keyword) AS relevance FROM clip c INNER JOIN clip_category cc ON c.category_id=cc.id LEFT JOIN admin a ON c.member_id=a.id LEFT JOIN `admin` b ON c.subcp_id = b.id WHERE MATCH(title) AGAINST($keyword)>1 ORDER BY relevance DESC LIMIT $limit OFFSET $offset";
        $this->_db->query($sql);

        return $this->_db->fetchRowSet();
    }

    public function countAllBySearch($keyword) {
        $keyword =  mysql_escape_string($keyword);
        $keyword = $this->_db->valueQuote($keyword);
        $sql = "SELECT count(*) AS 'count' FROM clip c INNER JOIN clip_category cc ON c.category_id=cc.id WHERE MATCH(title) AGAINST($keyword)>1";
        $this->_db->query($sql);
        $row = $this->_db->fetchRow();

        return $row ? $row['count'] : 0;
    }

    public function countAll($userId=0, $condition = '', $visible = 1) {
        $_owner = $userId ? " WHERE (c.member_id=$userId OR c.subcp_id=$userId)" : " WHERE 1 ";
        if (!$userId) {
            $condition = ($condition != '') ? (' WHERE ' . $condition) : '';
            $sql = "SELECT COUNT(c.id) as numrow FROM clip c ";
            $sql .= "INNER JOIN clip_category cc ON c.category_id = cc.id AND cc.visible = $visible ";
            $sql .= $condition;
        } else {
            $condition = ($condition != '') ? ('AND ' . $condition) : '';
            $sql = "SELECT COUNT(c.id) as numrow FROM clip c ";
            $sql .= "INNER JOIN clip_category cc ON c.category_id = cc.id AND cc.visible = $visible ";
            $sql .= $_owner . $condition;
        }
        //echo $sql;
        $this->_db->query($sql);
        $row = $this->_db->fetchRow();
        return $row['numrow'];
    }

    public function countAllRadio($catId, $condition = '') {
        $condition = $condition ? "AND $condition" : '';

        $sql = "SELECT count(*) as 'count' FROM clip c
                    LEFT JOIN clip_category cc ON c.category_id = cc.id
                WHERE cc.visible=0 $condition";

        $this->_db->query($sql);
        $row = $this->_db->fetchRow();

        return $row ? $row['count'] : 0;
    }

    public function save($data, $videoId, $can_edit_price) {
        $title = $this->_db->valueQuote($data['title']);
        $titleVn = $this->_db->valueQuote(stripText($data['title_vn']));
        $description = $this->_db->valueQuote($data['description']);
        $descriptionVn = $this->_db->valueQuote(stripText($data['description_vn']));
        $tag = $this->_db->valueQuote($data['tag']);
        $categoryId = intval($data['category_id']);
        $subCpId = intval($data['subcp_id']);
        $uid = $_SESSION['userid'];

        if ($can_edit_price) {
            $price = intval($data['price']);
            $download_price = intval($data['download_price']);
        } else {
            $price = 'price';
            $download_price = 'download_price';
        }
        if (empty($_POST['thumbnail']))
            $thumbnail = '';
        else
            $thumbnail=', thumbnail_version=thumbnail_version+1 ';
        $sql = "UPDATE clip SET title=$title, title_vn=$titleVn,
                description=$description, description_vn=$descriptionVn,
                category_id=$categoryId,
                tag=$tag,
                subcp_id=$subCpId,
                price=$price,
                download_price=$download_price,
                updated_by=$uid, updated_time=now()
                $thumbnail
                WHERE id=$videoId";
        return $this->_db->queryWrite($sql);
    }

    public function deleteFromList($list, $userId=0) {
        $adminId = $_SESSION['userid'];
        $videoIdList = $list;
        $list = "(" . implode(",", $list) . ")";
        if (!$userId) {
            // CM hoặc Admin xóa
            $sql = "UPDATE clip SET deleted=1, updated_by=$adminId, updated_time=now() WHERE id IN $list";
            $valueSet = array();
            foreach ($videoIdList as $videoId) {
                $valueSet[] = '(' . $videoId . ',' . $adminId . ',\'Quản trị xóa\')';
            }
            $valueSet = implode($valueSet, ',');
            $sqlInsert = "INSERT INTO clip_deleted (clip_id, deleted_by, reason) VALUES $valueSet ON DUPLICATE KEY UPDATE updated_time=now()";
            $this->_db->queryWrite($sqlInsert);
        } else {
            // Tự mình xóa clip của mình
            $sql = "UPDATE clip SET deleted=1 WHERE id IN $list AND member_id=" . $userId;
        }
        return $this->_db->queryWrite($sql);
    }

    public function getPendingVideoDetail($videoId) {
        $sql = "SELECT clip.*, ms.address AS server, ms.directory, ms.streaming_address AS streaming_server FROM clip LEFT JOIN movie_server ms ON clip.ms_id=ms.msID WHERE clip.id=$videoId AND clip.deleted=0 AND converted=1 AND active=0";
        $this->_db->query($sql);
        return $this->_db->fetchRow();
    }

    /* Video có thể duyệt không:
      - Đang được duyệt bởi một ai đó, thời gian expire chưa hết => không được
      - Đang được duyệt bởi một ai đó, thời gian expire đã hết   => được
      - Không có ai đang duyệt => được\
     */

    public function canApproveVideo($videoId) {
        $config = Vega_App::getInstance()->coreConfig;
        $timeToAprove = 5 * 60; // sau 5 phut ma khong approve thi nguoi khac se duoc xet duyet

        $sql = "SELECT * FROM tmp_approval t LEFT JOIN admin a ON t.admin_id = a.id WHERE clip_id=$videoId";
        $this->_db->query($sql);
        $row = $this->_db->fetchRow();
        if ($row) {
            if ($row['admin_id'] != $_SESSION['userid']) {
                if (time() > strtotime($row['expired_time'])) {
                    $expired_time = date('Y-m-d H:i:s', time() + $timeToAprove);
                    $sql = "UPDATE tmp_approval SET admin_id=" . $_SESSION['userid'] . ", expired_time='$expired_time'
                            WHERE clip_id=$videoId";
                    $this->_db->query($sql);
                    return true;
                } else {
                    $_SESSION['msg'] = 'Video đang được duyệt bởi ' . $row['name'];
                    return false;
                }
            } else {
                return true;
            }
        } else {
            $expired_time = date('Y-m-d H:i:s', time() + $timeToAprove);
            $sql = "INSERT INTO tmp_approval SET clip_id=$videoId, admin_id=" . $_SESSION['userid'] . ", expired_time='$expired_time'";
            $this->_db->query($sql);

            return true;
        }
    }

    /*
     * Hàm từ chối kích hoạt video do vi phạm
     * - thiết lập giá trị 1 cho trường deleted, active=1 trong bảng clip [return]
     * - thêm vào bảng clip_deleted clip, lý do và người xóa
     */

    public function declineVideo($reason, $videoId) {
        $userId = $_SESSION['userid'];
        $reason = $this->_db->valueQuote($reason);
        $sql1 = "UPDATE clip SET deleted=1, active=1, updated_time=now(), updated_by=$userId WHERE id=$videoId";
        $sql2 = "INSERT INTO clip_deleted SET clip_id=$videoId, deleted_by=$userId, reason=$reason ON DUPLICATE KEY UPDATE updated_time=now()";

        $ret1 = $this->_db->queryWrite($sql1);
        $ret2 = $this->_db->queryWrite($sql2);
        return $ret1;
    }

    public function approveVideo($data, $videoId) {
        $title = $this->_db->valueQuote($data['title']);
        $titleVn = $this->_db->valueQuote(stripText($data['title']));
        $description = $this->_db->valueQuote($data['description']);
        $descriptionVn = $this->_db->valueQuote(stripText($data['description']));
        $tag = $this->_db->valueQuote($data['tag']);
        $source = $this->_db->valueQuote($data['source']);
        $categoryId = intval($data['category_id']);
        $userId = $_SESSION['userid'];
        $price = intval($data['price']);
        $download_price = intval($data['download_price']);
        $sql = "UPDATE clip SET title=$title, title_vn=$titleVn,
                description=$description, description_vn=$descriptionVn,
                tag=$tag,
                category_id=$categoryId,
                source=$source,
                price=$price,
                download_price=$download_price,
                active=1,
                updated_by=$userId, updated_time=now(),
                approved_by=$userId, approved_time=now()
                WHERE id=$videoId";
        return $this->_db->queryWrite($sql);
    }

    public function cancelApproving($videoId) {
        $sql = "DELETE FROM tmp_approval WHERE clip_id=$videoId AND admin_id=" . $_SESSION['userid'];
        return $this->_db->queryWrite($sql);
    }

    /*
     * Hàm lấy id của video đang chờ duyệt tiếp theo
     * @return unsigned int if exists pending video you can approve
     */

    public function getIdNextPendingVideo() {
        $userid = $_SESSION['userid'];
        $sql = "SELECT * FROM clip c LEFT JOIN tmp_approval ta ON c.id = ta.clip_id
                WHERE (ta.admin_id IS NULL OR ta.admin_id=$userid OR ta.expired_time < now()) 
                AND converted=1 AND deleted=0 AND active=0 ORDER BY created_time DESC";
        $this->_db->query($sql);
        $row = $this->_db->fetchRow();
        if ($row)
            return $row['id'];
        else
            return 0;
    }

    /*
     * Hàm lấy danh sách các lý do vi phạm
     * làm clip không được kích hoạt (bị decline thay vì approve)
     */

    public function getListIgnoreReason() {
        $sql = "SELECT * FROM ignore_reason";
        $this->_db->query($sql);
        return $this->_db->fetchRowSet();
    }

    /*
     * Hàm thêm một video vào danh sách video chọn lọc
     * @last modified time      11/11/2009
     *      CHANGE:
     *          Moi vao order = 1, uu tien hien thi
     * @param   $videoId int
     */

    public function addFeaturedVideo($videoId) {
        $updaterId = $_SESSION['userid'];
        $sql = "UPDATE clip_featured SET `order`=`order` + 1";
        $ret = $this->_db->queryWrite($sql);

        $order = 1;
        $sql = "INSERT INTO clip_featured SET clip_id=$videoId, updated_by=$updaterId, `order`=$order, updated_time=now(), status=1 ON DUPLICATE KEY UPDATE updated_time=now()";
        $ret = $this->_db->queryWrite($sql);

        $this->reOrderFeaturedVideo();

        return $ret;
    }

    public function addHotVideo($videoId, $daily = 0) {
        $updaterId = $_SESSION['userid'];
        $sql = "INSERT INTO clip_hot SET clip_id=$videoId, updated_by=$updaterId, updated_time=now(), daily = $daily
                    ON DUPLICATE KEY UPDATE updated_time=now(), daily = $daily, updated_by=$updaterId";
        $ret = $this->_db->queryWrite($sql);
        return $ret;
    }

    /*
     * Hàm thêm một video radio vào danh sách radio chọn lọc
     * @last modified time      08/04/2011
     *      CHANGE:
     *          Moi vao order = 1, uu tien hien thi
     * @param   $videoId int
     */

    public function addFeaturedRadio($videoId) {
        $updaterId = $_SESSION['userid'];
        $sql = "UPDATE clip_radio_featured SET `order`=`order` + 1";
        $ret = $this->_db->queryWrite($sql);

        $order = 1;
        $sql = "INSERT INTO clip_radio_featured SET clip_id=$videoId, updated_by=$updaterId, `order`=$order, updated_time=now(), status=1 ON DUPLICATE KEY UPDATE updated_time=now()";
        $ret = $this->_db->queryWrite($sql);

        $this->reOrderFeaturedRadio();

        return $ret;
    }

    /*
     * Hàm lấy danh sách id các video chọn lọc
     * Danh sách này được dùng để đối chiếu hiển thị nút
     * thêm vào chọn lọc khi quản lý video.
     * if (isset($list[$videoId])) ~ video da trong danh
     * sach chon loc
     */

    public function getIdListFeaturedVideo() {
        $sql = "SELECT clip_id FROM clip_featured LEFT JOIN clip ON clip_id=id WHERE converted=1 AND active=1 AND deleted=0";
        $list = array();
        $rows = $this->_db->fetchRowSet($sql);
        foreach ($rows as $row) {
            $list[$row['clip_id']] = true;
        }
        return $list;
    }

    public function getIdListHotVideo($daily = 0) {
        $sql = "SELECT clip_id
                    FROM clip_hot LEFT JOIN clip ON clip_id=id
                    WHERE converted=1 AND active=1 AND deleted=0 AND daily = $daily";
        $list = array();
        $rows = $this->_db->fetchRowSet($sql);
        foreach ($rows as $row) {
            $list[$row['clip_id']] = true;
        }
        return $list;
    }

    /*
     * Hàm lấy danh sách video chọn lọc, với các thông tin chi tiết
     * như người đăng là ai (JOIN admin), chuyên mục nào (JOIN clip_category)
     */

    public function getFeaturedVideo($page, $limit) {
        $offset = $limit * ($page - 1);
        $_limit = ' LIMIT ' . $limit;
        $_offset = ' OFFSET ' . $offset;

        $sql = "SELECT a.name AS owner,
                       cc.name AS category_name,
                       cf.order,
                       c. *
                FROM clip_featured cf
                     LEFT JOIN clip c ON cf.clip_id = c.id
                     LEFT JOIN admin a ON c.member_id = a.id
                     LEFT JOIN clip_category cc ON cc.id = c.category_id
                WHERE active=1 AND deleted=0 AND converted=1 
                ORDER BY `order` ASC
                $_limit $_offset
                ";
        return $this->_db->fetchRowSet($sql);
    }

    public function getHotVideo($date, $daily = 0) {
        $sql = "SELECT a.name AS owner,
                       cc.name AS category_name,
                       c. *
                FROM clip_hot ch
                     LEFT JOIN clip c ON ch.clip_id = c.id
                     LEFT JOIN admin a ON c.member_id = a.id
                     LEFT JOIN clip_category cc ON cc.id = c.category_id
                WHERE c.active=1 AND c.deleted=0 AND c.converted=1 AND daily = $daily
                ORDER BY ch.updated_time DESC ";
        //echo $sql;
        return $this->_db->fetchRowSet($sql);
    }

    /*
     * Hàm lấy danh sách radio chọn lọc, với các thông tin chi tiết
     * như người đăng là ai (JOIN admin), chuyên mục nào (JOIN clip_category)
     */

    public function getFeaturedRadio($page, $limit) {
        $offset = $limit * ($page - 1);
        $_limit = ' LIMIT ' . $limit;
        $_offset = ' OFFSET ' . $offset;

        $sql = "SELECT a.name AS owner,
                       cc.name AS category_name,
                       cf.order,
                       c. *
                FROM clip_radio_featured cf
                     LEFT JOIN clip c ON cf.clip_id = c.id
                     LEFT JOIN admin a ON c.member_id = a.id
                     LEFT JOIN clip_category cc ON cc.id = c.category_id
                WHERE active=1 AND deleted=0 AND converted=1
                ORDER BY `order` ASC
                $_limit $_offset
                ";
        return $this->_db->fetchRowSet($sql);
    }

    /*
     * Hàm xóa 1 danh sách các video (id) ra khỏi danh sách video chọn lọc
     * @param   $list array int
     *
     * Sau khi xóa sẽ sắp xếp lại thứ tự, tức là gọi tới hàm
     * reOrderFeaturedVideo
     */

    public function deleteFeaturedVideoFromList($list) {
        $list = "(" . implode(",", $list) . ")";
        $sql = "DELETE FROM clip_featured WHERE clip_id IN $list";
        $ret = $this->_db->queryWrite($sql);

        $this->reOrderFeaturedVideo();
        return $ret;
    }

    public function deleteHotVideoFromList($list, $daily = 0) {
        $list = "(" . implode(",", $list) . ")";
        $sql = "DELETE FROM clip_hot WHERE clip_id IN $list AND daily = $daily";
        $ret = $this->_db->queryWrite($sql);
        return $ret;
    }

    /*
     * Hàm xóa 1 danh sách các radio (id) ra khỏi danh sách radio chọn lọc
     * @param   $list array int
     *
     * Sau khi xóa sẽ sắp xếp lại thứ tự, tức là gọi tới hàm
     * reOrderFeaturedRadio
     */

    public function deleteFeaturedRadioFromList($list) {
        $list = "(" . implode(",", $list) . ")";
        $sql = "DELETE FROM clip_radio_featured WHERE clip_id IN $list";
        $ret = $this->_db->queryWrite($sql);

        $this->reOrderFeaturedRadio();
        return $ret;
    }

    /*
     * Hàm thêm một danh sách các video (id) vào
     * danh sách chọn lọc
     * @param   $list array int
     */

    public function addListToFeaturedVideo($list) {
        
    }

    /*
     * Hàm lấy số video chọn lọc
     * cũng chính là max của trường order
     * (Khi xóa clip ra khỏi danh sách chọn lọc thì phải re-order theo thứ tự từ 1)
     */

    public function getNumberFeaturedVideo() {
        $sql = "SELECT COUNT(clip_id) as num FROM clip_featured LEFT JOIN clip ON clip_id=id WHERE active=1 AND deleted=0 AND converted=1";
        $this->_db->query($sql);
        $row = $this->_db->fetchRow();
        return $row['num'];
    }

    /*
     * Hàm lấy số radio chọn lọc
     * cũng chính là max của trường order
     * (Khi xóa clip ra khỏi danh sách chọn lọc thì phải re-order theo thứ tự từ 1)
     */

    public function getNumberFeaturedRadio() {
        $sql = "SELECT COUNT(clip_id) as num FROM clip_radio_featured LEFT JOIN clip ON clip_id=id WHERE active=1 AND deleted=0 AND converted=1";
        $this->_db->query($sql);
        $row = $this->_db->fetchRow();
        return $row['num'];
    }

    /*
     * Hàm thay đổi (di chuyển) thứ tự hiển thị của một video chọn lọc
     *
     */

    public function moveFeaturedVideo($videoId, $curOrder, $newOrder, $maxOrder) {
        // Chuyen len dau danh sach
        if ($newOrder == 1) {
            $sql = "UPDATE clip_featured SET `order`=`order` + 1 WHERE `order` < $curOrder";
            $this->_db->queryWrite($sql);

            $sql = "UPDATE clip_featured SET `order`=$newOrder WHERE clip_id=$videoId";
            return $this->_db->queryWrite($sql);
        } elseif ($newOrder == $maxOrder) {
            $sql = "UPDATE clip_featured SET `order`=`order` - 1 WHERE `order` > $curOrder";
            $this->_db->queryWrite($sql);

            $sql = "UPDATE clip_featured SET `order`=$newOrder WHERE clip_id=$videoId";
            return $this->_db->queryWrite($sql);
        } elseif ($newOrder == $curOrder + 1 ||
                $newOrder == $curOrder - 1
        ) {//chuyển xuống dưới | lên trên
            $sql = "UPDATE clip_featured SET `order`=$curOrder WHERE `order`=$newOrder";
            $this->_db->queryWrite($sql);

            $sql = "UPDATE clip_featured SET `order`=$newOrder WHERE clip_id=$videoId";
            return $this->_db->queryWrite($sql);
        } else {
            return true;
        }
    }

    /*
     * Hàm thay đổi (di chuyển) thứ tự hiển thị của một radio chọn lọc
     *
     */

    public function moveFeaturedRadio($videoId, $curOrder, $newOrder, $maxOrder) {
        // Chuyen len dau danh sach
        if ($newOrder == 1) {
            $sql = "UPDATE clip_radio_featured SET `order`=`order` + 1 WHERE `order` < $curOrder";
            $this->_db->queryWrite($sql);

            $sql = "UPDATE clip_radio_featured SET `order`=$newOrder WHERE clip_id=$videoId";
            return $this->_db->queryWrite($sql);
        } elseif ($newOrder == $maxOrder) {
            $sql = "UPDATE clip_radio_featured SET `order`=`order` - 1 WHERE `order` > $curOrder";
            $this->_db->queryWrite($sql);

            $sql = "UPDATE clip_radio_featured SET `order`=$newOrder WHERE clip_id=$videoId";
            return $this->_db->queryWrite($sql);
        } elseif ($newOrder == $curOrder + 1 ||
                $newOrder == $curOrder - 1
        ) {//chuyển xuống dưới | lên trên
            $sql = "UPDATE clip_radio_featured SET `order`=$curOrder WHERE `order`=$newOrder";
            $this->_db->queryWrite($sql);

            $sql = "UPDATE clip_radio_featured SET `order`=$newOrder WHERE clip_id=$videoId";
            return $this->_db->queryWrite($sql);
        } else {
            return true;
        }
    }

    /*
     * Hàm sắp xếp lại thứ tự hiển thị video chọn lọc
     * Hàm liên quan: deleteFeaturedVideoFromList($list)
     */

    public function reOrderFeaturedVideo() {
        $sql = "SELECT clip_id FROM clip_featured LEFT JOIN clip ON clip_id=id WHERE active=1 AND deleted=0 AND converted=1 ORDER BY `order` ASC";
        $this->_db->query($sql);
        $rows = $this->_db->fetchRowSet();
        $index = 1;
        $ret = true;
        foreach ($rows as $row) {
            $id = $row['clip_id'];
            $sql = "UPDATE clip_featured SET `order`=$index WHERE clip_id=$id";
            if (!($this->_db->queryWrite($sql)))
                $ret = false;
            $index++;
        }
        return $ret;
    }

    /*
     * Hàm sắp xếp lại thứ tự hiển thị video radio chọn lọc
     * Hàm liên quan: deleteFeaturedRadioFromList($list)
     */

    public function reOrderFeaturedRadio() {
        $sql = "SELECT clip_id FROM clip_radio_featured LEFT JOIN clip ON clip_id=id WHERE active=1 AND deleted=0 AND converted=1 ORDER BY `order` ASC";
        $this->_db->query($sql);
        $rows = $this->_db->fetchRowSet();
        $index = 1;
        $ret = true;
        foreach ($rows as $row) {
            $id = $row['clip_id'];
            $sql = "UPDATE clip_radio_featured SET `order`=$index WHERE clip_id=$id";
            if (!($this->_db->queryWrite($sql)))
                $ret = false;
            $index++;
        }
        return $ret;
    }

    public function getListBehavior($page, $limit, $object, $admin, $object_name, $object_id, $txtSearch = '') {
        $txtSearch = mysql_escape_string($txtSearch);
        $offset = $limit * ($page - 1);
        $_limit = ' LIMIT ' . $limit;
        $_offset = ' OFFSET ' . $offset;
        //$sql = "SELECT a.*,ad.name, ad.id as admin_id, c.title FROM clip c, admin_session a, admin ad WHERE a.object_id = c.id AND ad.id = a.admin_id ";
        $sql = "SELECT a.*,ad.name, ad.id as admin_id, ";
        $sql .= " CASE WHEN c.title <> '' THEN c.title ELSE cs.title ";
        $sql .= " END title ";
        $sql .= " FROM admin_session a ";

        $sql .= " LEFT JOIN admin ad ON ad.id = a.admin_id ";

        $sql .= " LEFT JOIN clip c ON a.object_id = c.id ";
        $sql .= " LEFT JOIN channel_schedule cs ON cs.id = a.object_id ";

        $sql .= " WHERE 1=1 ";
        if ($admin != '') {
            $sql .= " AND ad.id = '$admin'";
        }
        if ($object_name != '') {
            $sql .= " AND a.object = '$object_name'";
        }
        if ($object_id != '') {
            $sql .= " AND a.object_id = '$object_id'";
        }
        if ($txtSearch != '') {
            $sql .= " AND (c.title like '%$txtSearch%' OR ad.name like '%$txtSearch%')";
        }
        if ($object != '') {
            $sql .= " AND a.object = '$object'";
        }
        $sql .= ' ORDER BY created_time Desc ';
        $sql .= $_limit . $_offset;
        $this->_db->query($sql);
        $arrResult = $this->_db->fetchRowSet();
        $total = $this->rowCountAdmin($object, $admin, $object_name, $object_id, $txtSearch);
        return array('data' => $arrResult, 'total' => $total);
    }

    public function rowCountAdmin($object, $admin, $object_name, $object_id, $txtSearch = '') {
        $sql = "SELECT COUNT(a.id) as numrow FROM admin_session a ";
        $sql .= " LEFT JOIN clip c ON a.object_id = c.id ";
        $sql .= " LEFT JOIN admin ad ON ad.id = a.admin_id ";
        $sql .= " WHERE 1=1 ";
        if ($admin != '') {
            $sql .= " AND ad.id = '$admin'";
        }
        if ($object_name != '') {
            $sql .= " AND a.object = '$object_name'";
        }
        if ($object_id != '') {
            $sql .= " AND a.object_id = '$object_id'";
        }
        if ($txtSearch != '') {
            $sql .= " AND c.title like '%$txtSearch%'";
        }
        if ($object != '') {
            $sql .= " AND a.object = '$object'";
        }
        $this->_db->query($sql);
        $row = $this->_db->fetchRow();
        return $row['numrow'];
    }

    public function hideVideSex() {
        $sql = "UPDATE clip set deleted=99 where active = 1 AND (title like '%sex%' OR description like '%sex%'
                    OR title like '%nude%' OR description like '%nude%'
                    OR title like '%shock%' OR description like '%shock%'
                    OR title like '%khỏa thân%' OR description like '%khỏa thân%'
                    OR title like '%sốc%' OR description like '%sốc%')";
        return $this->_db->queryWrite($sql);
    }

    public function getHotPackageVideo() {
        $sql = "SELECT * FROM clip_hot_news_price WHERE deleted = 0";
        $this->_db->query($sql);
        $results = $this->_db->fetchRowSet();
        return $results;
    }

    public function insertVodHot($data) {
        $sql = "INSERT INTO clip_hot_news_price(id, name, price, updated_by, updated_time, created_time) VALUES(";
        $sql .= $data['id'];
        $sql .= ", '" . $data['name'] . "'";
        $sql .= ", " . $data['price'];
        $sql .= ", " . $data['user_id'];
        $sql .= ", now()";
        $sql .= ", now()";
        $sql .= ")";
        $sql .= " ON DUPLICATE KEY UPDATE updated_time=now(), deleted =0, price = " . $data['price'] . ", name = '" . $data['name'] . "' , updated_by = " . $data['user_id'];
        //echo $sql; exit;
        return $this->_db->queryWrite($sql);
    }

    public function getIdVodHotPackage() {
        $sql = "SELECT id FROM clip_hot_news_price WHERE deleted = 0 ORDER BY id DESC LIMIT 1";
        $this->_db->query($sql);
        $results = $this->_db->fetchRow();
        return ($results) ? $results['id'] : 0;
    }

    public function getHotPackageVideoById($id) {
        if ($id) {
            $id = intval($id);
            $sql = "SELECT * FROM clip_hot_news_price WHERE id = $id AND deleted = 0";
            $this->_db->query($sql);
            $results = $this->_db->fetchRow();
            return $results;
        } else {
            return array();
        }
    }

    public function deleteVodHot($id) {
        $id = intval($id);
        $sql = "UPDATE clip_hot_news_price SET deleted = 1 WHERE id = $id";
        return $this->_db->queryWrite($sql);
    }

    public function updateStatusSubvod($daily = 1) {
        $daily = intval($daily);
        //$sql = "UPDATE clip_hot_registration SET `status`=0 WHERE daily = $daily AND deleted=0 AND DATEDIFF(now(), charged_time)>=7";
        $sql = "UPDATE clip_hot_registration SET `status`=0 WHERE daily = $daily AND deleted=0";
        return $this->_db->queryWrite($sql);
    }

    public function updateVnColumnForClip() {
        $sql = "SELECT id, title, description FROM clip";
        $this->_db->query($sql);
        $results = $this->_db->fetchRowSet();
        foreach ($results as $data) {
            $titleVn = $this->_db->valueQuote(stripText($data['title']));
            $descriptionVn = $this->_db->valueQuote(stripText($data['description']));
            $id = $data['id'];
            $sql = "UPDATE clip SET title_vn=$titleVn, description_vn=$descriptionVn WHERE id=$id";
            $this->_db->queryWrite($sql);
        }        
    }

}